package com.example.zsf.activity.mobile;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.zsf.R;
import com.example.zsf.ZSFApplication;
import com.example.zsf.activity.account.LoginActivity;
import com.example.zsf.activity.common.ImageBrowserActivity;
import com.example.zsf.adapter.MobileDetailListAdapter;
import com.example.zsf.base.Presenter;
import com.example.zsf.base.Result;
import com.example.zsf.base.ZSFBaseActivity;
import com.example.zsf.base.ZSFGlobal;
import com.example.zsf.model.MobileDetailModel;
import com.example.zsf.presenter.MobilePresenter;
import com.example.zsf.view.CollectedInfoDialog;
import com.example.zsf.view.EnterInfomationDialog;
import com.netease.nis.captcha.Captcha;
import com.netease.nis.captcha.CaptchaConfiguration;
import com.netease.nis.captcha.CaptchaListener;
import com.orhanobut.logger.Logger;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerAdapter;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.listener.OnPageChangeListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;

import static cn.jzvd.Jzvd.SCREEN_NORMAL;
import static cn.jzvd.Jzvd.STATE_PLAYING;

public class MobileDetailActivity extends ZSFBaseActivity {
    @BindView(R.id.banner)
    Banner<MobileDetailModel.BannerImageInfo, CustomBannerAdapter> banner;
    @BindView(R.id.indicator)
    CircleIndicator indicator;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.button3)
    Button grab_bt;
    @BindView(R.id.textView35)
    TextView bannerTitle_tv;
    @BindView(R.id.textView36)
    TextView bannerPage_tv;
    @BindView(R.id.content_im)
    ImageView contentIm;
    @BindView(R.id.favorite_bt)
    Button favoriteBt;
    @BindView(R.id.textView22)
    TextView title_tv;
    @BindView(R.id.textView33)
    TextView remark_tv;
    @BindView(R.id.button2)
    Button url_bt;
    @BindView(R.id.share_bt)
    Button share_bt;
    @BindView(R.id.textView30)
    TextView mark1_tv;
    @BindView(R.id.textView31)
    TextView mark2_tv;
    @BindView(R.id.textView32)
    TextView mark3_tv;
    @BindView(R.id.textView40)
    TextView giftInfo_tv;
    @BindView(R.id.constraintLayout6)
    ConstraintLayout grab_container;
    @BindView(R.id.textView41)
    TextView textView41;
    @BindView(R.id.constraintLayout7)
    LinearLayout constraintLayout7;
    @BindView(R.id.textView24)
    TextView time_tv;


    private String id;
    private String image_url;
    private boolean needGrab;
    private String time;


    private CustomBannerAdapter customBannerAdapter;
    private MobileDetailListAdapter mobileDetailListAdapter;

    private MobileDetailModel data;

    private CountDownTimer countDownTimer;

    private CaptchaConfiguration configuration;

    public static final int MobileDetailRequestCode = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mobile_detail);

        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(lp);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        Logger.d(ConvertUtils.px2dp(getStatusBarHeight(this)));


        ButterKnife.bind(this);

        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        image_url = intent.getStringExtra("image_url");
        needGrab = intent.getBooleanExtra("need_grab", false);
        time = intent.getStringExtra("time");

        initUI();
        initData();
    }


    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    private void initData() {
        initCaptcha();
        requestAdInfo();
    }

    private void initUI() {
        customBannerAdapter = new CustomBannerAdapter(null, this);
        banner.addBannerLifecycleObserver(this)
                .setIndicator(indicator, false)
                .setAdapter(customBannerAdapter, false)
                .addOnPageChangeListener(new OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    }

                    @Override
                    public void onPageSelected(int position) {
                        Logger.d("selected " + position);
                        // 更新文字描述 更新右上角 1/2
                        if (data != null) {
                            bannerPage_tv.setText((position + 1) + "/" + data.getAds_img().size());
                            bannerTitle_tv.setText(data.getAds_img().get(position).getTitle());
                        }
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                })
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(Object data, int position) {
                        MobileDetailModel.BannerImageInfo info = (MobileDetailModel.BannerImageInfo) data;
                        if (info.getType() != 2) {
                            ArrayList<MobileDetailModel.BannerImageInfo> imageInfos = new ArrayList<>();
                            boolean isHasVideo = false;
                            for (int i = 0; i < MobileDetailActivity.this.data.getAds_img().size(); i++) {
                                MobileDetailModel.BannerImageInfo tempInfo = MobileDetailActivity.this.data.getAds_img().get(i);
                                if (tempInfo.getType() == 2) {
                                    isHasVideo = true;
                                    continue;
                                }
                                imageInfos.add(tempInfo);
                            }
                            Intent intent = new Intent(MobileDetailActivity.this, ImageBrowserActivity.class);
                            intent.putParcelableArrayListExtra("banner_image_infos", imageInfos);
                            intent.putExtra("index", position - (isHasVideo ? 1 : 0));
                            startActivityForResult(intent, MobileDetailRequestCode);
                        }
                    }
                });


        Glide.with(this).load(image_url).into(contentIm);
        grab_container.setVisibility(needGrab ? View.VISIBLE : View.GONE);
        textView41.setVisibility(needGrab ? View.VISIBLE : View.GONE);
        constraintLayout7.setVisibility(needGrab ? View.VISIBLE : View.GONE);

        time_tv.setText(time);


        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mobileDetailListAdapter = new MobileDetailListAdapter(this, R.layout.item_mobile_detail, null);
        recyclerView.setAdapter(mobileDetailListAdapter);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MobileDetailRequestCode && data != null) {
            int index = data.getIntExtra("index", 0);
            boolean isHasVideo = false;
            for (int i = 0; i < MobileDetailActivity.this.data.getAds_img().size(); i++) {
                MobileDetailModel.BannerImageInfo tempInfo = MobileDetailActivity.this.data.getAds_img().get(i);
                if (tempInfo.getType() == 2) {
                    isHasVideo = true;
                    break;
                }
            }
            banner.setCurrentItem(index + (isHasVideo ? 1 : 0));
        }
    }

    @OnClick(R.id.back_im)
    public void onBackImClicked() {
        finish();
    }

    @OnClick(R.id.button3)
    public void onButton3Clicked() {
        if (!ZSFGlobal.checkLogoutStatus(new ZSFGlobal.AccountCallBack() {
            @Override
            public void noneauth() {
                Intent intent = new Intent(MobileDetailActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        })) {
            if (grab_bt.getText().toString().equals("待填写")) {
                EnterInfomationDialog enterInfomationDialog = new EnterInfomationDialog(this, data, null, new EnterInfomationDialog.EnterInfoListener() {
                    @Override
                    public void confirmCallBack() {
                        requestAdInfo();
                    }
                });
                enterInfomationDialog.show();
            } else if (grab_bt.getText().toString().equals("开抢")) {
                Captcha captcha = Captcha.getInstance().init(configuration);
                captcha.validate();
            } else {
                if (data.getRcv_data() != null && data.getRcv_data().getData_user() != null) {
                    CollectedInfoDialog collectedInfoDialog = new CollectedInfoDialog(this, data.getRcv_data().getData_user(), null);
                    collectedInfoDialog.show();
                }
            }
        }


    }

    @OnClick({R.id.favorite_bt, R.id.share_bt, R.id.button2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.favorite_bt: {
                if (!ZSFGlobal.checkLogoutStatus(new ZSFGlobal.AccountCallBack() {
                    @Override
                    public void noneauth() {
                        Intent intent = new Intent(MobileDetailActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }
                })) {
                    requestFavorite();
                }
            }
            break;
            case R.id.share_bt: {
                if (!ZSFGlobal.checkLogoutStatus(new ZSFGlobal.AccountCallBack() {
                    @Override
                    public void noneauth() {
                        Intent intent = new Intent(MobileDetailActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }
                })) {
                    copy(url_bt.getText().toString());
                    ToastUtils.showLong("游戏链接已复制，快去邀请好友一起玩");
                }
            }
            break;
            case R.id.button2:// 网址
            {
                copy(url_bt.getText().toString());
                ToastUtils.showLong("复制成功");
            }
            break;
        }
    }

    private void requestAdInfo() {
        disposed(MobilePresenter.getAdInfo(id, new Presenter.PresenterListener<Result<MobileDetailModel>>() {
            @Override
            public void onSuccess(Result<MobileDetailModel> object) {
                //逻辑需要拆分
                if (object.code.equals("1")) {

                    data = object.data;

                    List<MobileDetailModel.BannerImageInfo> images = object.data.getAds_img();

                    if (images.size() > 0) {
                        bannerPage_tv.setText("1/" + images.size());
                        bannerTitle_tv.setText(images.get(0).getTitle());
                    } else {
                        MobileDetailModel.BannerImageInfo bannerImageInfo = new MobileDetailModel.BannerImageInfo();
                        bannerImageInfo.setImg_url("");
                        images.add(bannerImageInfo);
                        bannerPage_tv.setText("0/0");
                        bannerTitle_tv.setVisibility(View.GONE);
                    }

                    customBannerAdapter.setDatas(images);
                    customBannerAdapter.notifyDataSetChanged();

                    //是否关注
                    if (object.data.getAds_follow().equals("0")) {
                        favoriteBt.setText("关注");
                        favoriteBt.setBackgroundResource(R.drawable.bg_title_blue);
                    } else {
                        favoriteBt.setText("已关注");
                        favoriteBt.setBackgroundResource(R.drawable.bg_title_grey);
                    }

                    title_tv.setText(object.data.getAds_name());
                    remark_tv.setText(object.data.getAds_js());
                    url_bt.setText(object.data.getAds_url());

                    int priceStart = 5;
                    int priceEnd = priceStart + object.data.getGift_price().length();
                    int numStart = priceEnd + 4;
                    int numEnd = numStart + object.data.getGift_last_num().length();
                    SpannableString spannableString = new SpannableString("送充值  " + object.data.getGift_price() + "元 剩余" + object.data.getGift_last_num() + "份");
                    ForegroundColorSpan foregroundColorSpan1 = new ForegroundColorSpan(getResources().getColor(R.color.colorTitleRed));
                    ForegroundColorSpan foregroundColorSpan2 = new ForegroundColorSpan(getResources().getColor(R.color.colorTitleRed));
                    spannableString.setSpan(foregroundColorSpan1, priceStart, priceEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableString.setSpan(foregroundColorSpan2, numStart, numEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    giftInfo_tv.setText(spannableString);


                    //status_bt设置抢购状态，
                    if (object.data.getRcv_data() != null && object.data.getRcv_data().getData_user() != null && object.data.getRcv_data().getData_user().getRcv_status() != null) {
                        //已经领取了
                        int status = Integer.parseInt(object.data.getRcv_data().getData_user().getRcv_status());
                        switch (status) {
                            case 0:
                                grab_bt.setText("待充值");
                                grab_bt.setBackground(getResources().getDrawable(R.drawable.bg_title_orange));
                                break;
                            case 1:
                                grab_bt.setText("已充值");
                                grab_bt.setBackground(getResources().getDrawable(R.drawable.bg_title_green));
                                break;
                            case 2:
                                grab_bt.setText("异常");
                                grab_bt.setBackground(getResources().getDrawable(R.drawable.bg_mark_red));
                                break;
                            case 3:
                                grab_bt.setText("已退回");
                                grab_bt.setBackground(getResources().getDrawable(R.drawable.bg_mark_red));
                                break;
                            case 4:
                                grab_bt.setText("待填写");
                                grab_bt.setBackground(getResources().getDrawable(R.drawable.bg_title_green));
                                break;
                        }
                    } else {
                        // 没领的时候
                        long startTime = Long.parseLong(object.data.getGift_start_time());
                        long dis = startTime - TimeUtils.getNowMills() / 1000;
                        if (dis > 0) {
                            grab_bt.setBackground(getResources().getDrawable(R.drawable.bg_mark_red));
                            //未到时间
                            if (countDownTimer != null) {
                                countDownTimer.cancel();
                            }
                            countDownTimer = new CountDownTimer(dis * 1000, 1000) {
                                @Override
                                public void onTick(long millisUntilFinished) {
                                    grab_bt.setText(TimeUtils.getFitTimeSpanByNow(startTime * 1000, 4));
                                }

                                @Override
                                public void onFinish() {
                                    requestAdInfo();
                                }
                            };
                            countDownTimer.start();
                        } else {
                            if (Integer.parseInt(object.data.getGift_last_num()) > 0) {
                                grab_bt.setText("开抢");
                                grab_bt.setBackground(getResources().getDrawable(R.drawable.bg_title_blue));
                            } else {
                                grab_bt.setText("已抢光");
                                grab_bt.setBackground(getResources().getDrawable(R.drawable.bg_title_grey));
                                if (Double.parseDouble(object.data.getGift_price()) == 0) {
                                    grab_bt.setText("暂无礼包");
                                }
                            }
                        }
                    }

                    mark1_tv.setText(object.data.getAds_ip());
                    mark2_tv.setText(object.data.getAds_xl());
                    mark3_tv.setText(object.data.getAds_qq());

                    //刷新recycler view
                    if (object.data.getRcv_data() != null) {
                        mobileDetailListAdapter.setList(object.data.getRcv_data().getData_all());
                        mobileDetailListAdapter.notifyDataSetChanged();
                    }

                } else {
                    ToastUtils.showShort(object.msg);
                }
            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort(error);
            }
        }));
    }


    private void requestFavorite() {
        disposed(MobilePresenter.favorite(id, data.getAds_follow().equals("0") ? "1" : "0", new Presenter.PresenterListener<Result<HashMap>>() {
            @Override
            public void onSuccess(Result<HashMap> object) {
                if (object.code.equals("1")) {
                    requestAdInfo();
                } else {
                    ToastUtils.showShort(object.msg);
                }
            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort(error);
            }
        }));
    }

    private void requestGrab(String id, String validate) {
        disposed(MobilePresenter.grab(id, validate, new Presenter.PresenterListener<Result<HashMap>>() {
            @Override
            public void onSuccess(Result<HashMap> object) {
                if (object.code.equals("1")) {
                    requestAdInfo();
                    EnterInfomationDialog enterInfomationDialog = new EnterInfomationDialog(MobileDetailActivity.this, data, null, new EnterInfomationDialog.EnterInfoListener() {
                        @Override
                        public void confirmCallBack() {
                            requestAdInfo();
                        }
                    });
                    enterInfomationDialog.show();
                } else {
                    ToastUtils.showShort(object.msg);
                }
            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort(error);
            }
        }));
    }

    public void copy(String content) {
        if (!StringUtils.isEmpty(content)) {
            ClipboardManager cmb = (ClipboardManager) ZSFApplication.getInstance().getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(content.trim());
            ClipData clipData = ClipData.newPlainText(null, content);
            cmb.setPrimaryClip(clipData);
        }
    }

    private void initCaptcha() {
        configuration = new CaptchaConfiguration.Builder()
                .captchaId("cff4093947b8436d8fcf0c41aef44508")// 验证码业务id
                .mode(CaptchaConfiguration.ModeType.MODE_CAPTCHA)
                .listener(new CaptchaListener() {
                    @Override
                    public void onReady() {

                    }

                    @Override
                    public void onValidate(String s, String s1, String s2) {
                        if (Boolean.parseBoolean(s)) {
                            requestGrab(id, s1);
                        }
                    }

                    @Override
                    public void onError(int i, String s) {

                    }

                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onClose() {

                    }
                }) // 验证码回调监听器
                .timeout(1000 * 10) // 超时时间，一般无需设置
                .useDefaultFallback(true) // 是否使用默认降级方案，默认开启
                .hideCloseButton(false)//是否隐藏右上角关闭按钮，默认不隐藏
                .build(this);
    }


    class CustomBannerAdapter extends BannerAdapter<MobileDetailModel.BannerImageInfo, CustomBannerAdapter.BannerHolder> {
        private Context context;


        public CustomBannerAdapter(List<MobileDetailModel.BannerImageInfo> datas, Context context) {
            super(datas);
            this.context = context;
        }

        @Override
        public BannerHolder onCreateHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(context).inflate(R.layout.banner_mobile_detail,
                    parent, false);
            return new BannerHolder(inflate, viewType);
        }

        @Override
        public void onBindView(BannerHolder holder, MobileDetailModel.BannerImageInfo data, int position, int size) {
            if (data.getType() == 2) {
                holder.videoView.setVisibility(View.VISIBLE);
                if (holder.videoView.jzDataSource == null) {
                    String proxyUrl = ZSFApplication.getProxy(context).getProxyUrl(data.getVideo_url());
                    JZDataSource jzDataSource = new JZDataSource(proxyUrl);
                    holder.videoView.setUp(jzDataSource, SCREEN_NORMAL);
                    Glide.with(MobileDetailActivity.this).load(data.getImg_url()).into(holder.videoView.posterImageView);
                    holder.videoView.startVideo();
                }
            } else {
                holder.videoView.setVisibility(View.GONE);
                if (position == 0 && data.getImg_url().equals("")) {
                    holder.imageView.setImageResource(R.mipmap.loading);
                } else {
                    Glide.with(MobileDetailActivity.this).load(data.getImg_url()).placeholder(R.mipmap.loading1).into(holder.imageView);
                }
            }

        }


        class BannerHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.imageView9)
            ImageView imageView;
            @BindView(R.id.banner_wrap)
            FrameLayout bannerWrap;
            @BindView(R.id.videoView2)
            JzvdStd videoView;

            public BannerHolder(@NonNull View itemView, int viewType) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }

    }
}